/*
 * Copyright [duowan.com]
 * Web Site: http://www.duowan.com
 * Since 2005 - 2014
 */

package com.duowan.realtime.service.impl;

import com.duowan.realtime.dao.SqlJobDao;
import com.duowan.realtime.model.ServerInfo;
import com.duowan.realtime.model.SqlJob;
import com.duowan.realtime.service.SqlJobService;
import com.duowan.realtime.service.impl.ServerInfoServiceImpl.ServerInfoChecker;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.List;


/**
 * [SqlJob] 的业务操作实现类
 * 
 * @author badqiu email:badqiu(a)gmail.com
 * @version 1.0
 * @since 1.0
 */
@Service("sqlJobService")
@Transactional
public class SqlJobServiceImpl implements SqlJobService {

	protected static final Logger log = LoggerFactory.getLogger(SqlJobServiceImpl.class);
	
	private SqlJobDao sqlJobDao;
	/**增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写*/
	public void setSqlJobDao(SqlJobDao dao) {
		this.sqlJobDao = dao;
	}
	
	/** 
	 * 创建SqlJob
	 **/
	public SqlJob create(SqlJob sqlJob) {
	    Assert.notNull(sqlJob, "'sqlJob' must be not null");
        String duplicateJobName = getDuplicateJobName(sqlJob);
        if(StringUtils.isNotEmpty(duplicateJobName)){
            throw new IllegalArgumentException("设置的查询指标已经存在,请先删除，指标名称："+ duplicateJobName);
        }
	    sqlJobDao.insert(sqlJob);
	    return sqlJob;
	}

    /**
	 * 删除SqlJob
	 **/
    public void removeById(String sqlId) {
        sqlJobDao.deleteById(sqlId);
    }
    
	/** 
	 * 根据ID得到SqlJob
	 **/    
    public SqlJob getById(String sqlId) {
        return sqlJobDao.getSqlJobById(sqlId);
    }
    @Override
    public void updateErrorMessage(String sqlId, String errorMessage) {
        String trimedMessage = StringUtils.substring(errorMessage,0,4000);
        sqlJobDao.updateJobError(sqlId,trimedMessage);
    }

    @Override
    public List<SqlJob> getAllSqlJobs() {
        return sqlJobDao.getSqlJobs();
    }

    private String getDuplicateJobName(SqlJob job){
        SqlJob oldSqlJob = sqlJobDao.getSqlJobByQueryStatement(job.getQueryStatement());
        if(oldSqlJob !=null){
            return oldSqlJob.getName();
        }else{
            return "";
        }
    }

	@Override
	public int update(SqlJob sqlJob) {
		Assert.notNull(sqlJob,"'sqlJob' must be not null");
        return sqlJobDao.update(sqlJob);
	}
}
